﻿using System;
using System.Collections.Generic;
using System.Collections.ObjectModel;
using System.Globalization;
using System.Linq;
using System.Net;
using System.Reflection;
using System.Runtime.Serialization;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Navigation;
using ComicIsland.Common;
using ComicIsland.Common.WebHelper;
using Microsoft.Phone.Controls;
using Microsoft.Phone.Globalization;
using Microsoft.Phone.Shell;

namespace ComicIsland.App
{
    public partial class TestPage : PhoneApplicationPage
    {
        public TestPage()
        {
            InitializeComponent();
            //this.LoadBookStoreAlbum();
        }

        void TestWPDataUpdate(KEYS.WpDataUpdateType wpType)
        {

            //string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/comicslist_v2", "?", KEYS.REQUEST_QUERY_PLATFORM);
            string requestUrl = string.Concat("http://58.215.139.195", "/comic/wpdataupdate", "?", KEYS.REQUEST_QUERY_PLATFORM);

            Dictionary<string, object> parameters = new Dictionary<string, object>();
            
            if (wpType == KEYS.WpDataUpdateType.sync)
            {
                parameters.Add("type", KEYS.WpDataUpdateType.sync.ToString ());
                parameters.Add("channelurl", "");
                parameters.Add("ispush", "");
                parameters.Add("deviceuniqueid", "");
                parameters.Add("devicename", "");
                parameters.Add("devicemanufacturer", "");
                parameters.Add("osversion", "");
                parameters.Add("useragent", "");
                parameters.Add("syncdate", "");
                parameters.Add("addBooks", "");
                parameters.Add("deleteBooks", "");
            }
            else if (wpType == KEYS.WpDataUpdateType.bookHandle)
            {
                parameters.Add("type", KEYS.WpDataUpdateType.bookHandle.ToString());
                parameters.Add("wpId", "");
                parameters.Add("addBooks", "");
                parameters.Add("deleteBooks", "");
            }
            else if (wpType == KEYS.WpDataUpdateType.updateChannelurl)
            {
                parameters.Add("type", KEYS.WpDataUpdateType.updateChannelurl.ToString());
                parameters.Add("wpId", "");
                parameters.Add("channelurl", "");
            }
            else if (wpType == KEYS.WpDataUpdateType.updateOptions)
            {
                parameters.Add("type", KEYS.WpDataUpdateType.updateOptions.ToString());
                parameters.Add("wpId", "");
                parameters.Add("ispush", "");
            }
            PostClientHelper proxy = new PostClientHelper(parameters);
            LogHelper.LogInfo(requestUrl + "\t" + proxy.PostData.ToString(), this.GetType(), MethodBase.GetCurrentMethod());
            //            
            proxy.DownloadStringCompleted += (sender, e) =>
            {
            };
            proxy.DownloadStringAsync(new Uri(requestUrl, UriKind.Absolute));
        }



        void LoadBookStoreAlbum()
        {
            string requestUrl = string.Concat(KEYS.REQUEST_HOST, "/comic/getalbumlist?channelid=1&platformtype=1");
            WebTaskHelper webTask = new WebTaskHelper(new Uri(requestUrl));
            IAsyncResult ia = webTask.BeginWebTask(delegate(IAsyncResult callBackResult)
            {
                try
                {
                    this.Dispatcher.BeginInvoke(() =>
                    {
                        #region 获取结果处理
                        string result = webTask.EndWebTask(callBackResult);

                        if (string.IsNullOrWhiteSpace(result))
                        {
                            LogHelper.LogError("Result is empty.");
                            //MessageToastManager.Show("未获取到数据！", MessageToastLevel.Error);
                            return;
                        }
                        //
                        if (result.StartsWith("exception:"))
                        {
                            LogHelper.LogError(result);
                            //MessageToastManager.Show("网络连接失败！", MessageToastLevel.Error);
                            return;
                        }
                        LogHelper.LogInfo(result, this.GetType(), MethodBase.GetCurrentMethod());
                        //
                        var rootCharacterString = JSONHelper.Deserialize<TestJsonBookStoreAlbumBase>(result);
                        if (!(rootCharacterString != null && rootCharacterString.Info != null && rootCharacterString.Info.Count > 0))
                        {
                            //MessageToastManager.Show("返回结果为空！", MessageToastLevel.Error);
                        }
                        else
                        {
                            //ObservableCollection<StoreAlbum> storeAlbums = new ObservableCollection<StoreAlbum>();
                            foreach (TestJsonBookStoreAlbumInfo item in rootCharacterString.Info)
                            {
                                var areablocks = JSONHelper.Deserialize<ObservableCollection<TestJsonBookStoreAlbumInfoAreaBlock>>(item.Bigbooksjson);
                                item.Bigbooks = areablocks;
                                //if (areablocks != null && areablocks.Count > 0)
                                //{
                                //    foreach (TestJsonBookStoreAlbumInfoAreaBlock areablock in areablocks)
                                //    {
                                //        StoreAlbum album = new StoreAlbum();
                                //        album.Id = item.Id;
                                //        album.Name = item.Name;
                                //        album.Targetargument = item.Targetargument;
                                //        album.Targetmethod = item.Targetmethod;
                                //        //
                                //        album.Bigbookid = areablock.Bigbookid;
                                //        album.ComicName = areablock.Name;
                                //        album.Coverurl = areablock.Coverurl;
                                //        album.Progresstype = areablock.Progresstype;
                                //        album.Lastpartname = areablock.Lastpartname;
                                //        //
                                //        album.Bigbooks = areablocks;
                                //        //
                                //        storeAlbums.Add(album);                                       
                                //    }
                                //}
                            }
                            //按item.Id分组
                            var groupedAlbums =
                                from p in rootCharacterString.Info
                                orderby p.Id
                                group p by p.Name
                                    into AlbumName
                                    select new AlbumKeyedList<string, TestJsonBookStoreAlbumInfo>(AlbumName);

                            var items = new ObservableCollection<AlbumKeyedList<string, TestJsonBookStoreAlbumInfo>>(groupedAlbums);
                            foreach (var item in groupedAlbums)
                            {
                                LogHelper.LogInfo(item.Key);
                                var ts = item as List<TestJsonBookStoreAlbumInfo>;
                                foreach (TestJsonBookStoreAlbumInfo sa in ts)
                                {
                                    //LogHelper.LogInfo(string.Concat(sa.Name + "," + sa.Bigbooks));
                                }
                            }
                            this.Dispatcher.BeginInvoke(() =>
                            {
                                this.llsCategory.ItemsSource = new ObservableCollection<AlbumKeyedList<string, TestJsonBookStoreAlbumInfo>>(groupedAlbums);
                            });
                            //

                        }

                        #endregion 获取结果处理
                    });
                }
                catch (Exception err)
                {

                }
            }, webTask);
        }

        private void llsCategory_SelectionChanged(object sender, SelectionChangedEventArgs e)
        {

        }

        private void llsCategory_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void Border_Tap(object sender, System.Windows.Input.GestureEventArgs e)
        {

        }

        private void ListBox_ManipulationStarted(object sender, System.Windows.Input.ManipulationStartedEventArgs e)
        {
            LogHelper.LogInfo(e.ManipulationOrigin.X.ToString());
        }
    }

    public class TestA
    {
        public int Id { get; set; }
        public int ParentId { get; set; }

        public string ParentName { get; set; }

        public string Name { get; set; }
    }



    public class AlbumKeyedList<TKey, TItem> : List<TItem>
    {
        public TKey Key { protected set; get; }

        public AlbumKeyedList(TKey key, IEnumerable<TItem> items)
            : base(items)
        {
            Key = key;
        }

        public AlbumKeyedList(IGrouping<TKey, TItem> grouping)
            : base(grouping)
        {
            Key = grouping.Key;
        }
    }

    [DataContract]
    public class StoreAlbum
    {
        [DataMember(Name = "targetmethod")]
        public int Targetmethod { get; set; }

        [DataMember(Name = "id")]
        public int Id { get; set; }

        [DataMember(Name = "targetargument")]
        public string Targetargument { get; set; }

        [DataMember(Name = "name")]
        public string Name { get; set; }

        //
        [DataMember(Name = "bigbookid")]
        public int Bigbookid { get; set; }

        [DataMember(Name = "comicname")]
        public string ComicName { get; set; }

        [DataMember(Name = "progresstype")]
        public int Progresstype { get; set; }

        [DataMember(Name = "coverurl")]
        public string Coverurl { get; set; }

        [DataMember(Name = "lastpartname")]
        public string Lastpartname { get; set; }
        //
        [IgnoreDataMember]
        public ObservableCollection<TestJsonBookStoreAlbumInfoAreaBlock> Bigbooks { get; set; }

    }


    [DataContract]
    public class TestJsonBookStoreAlbumBase
    {

        [DataMember(Name = "code_msg")]
        public string CodeMsg { get; set; }

        [DataMember(Name = "code")]
        public int Code { get; set; }

        [DataMember(Name = "info")]
        public ObservableCollection<TestJsonBookStoreAlbumInfo> Info { get; set; }
    }


    [DataContract]
    public class TestJsonBookStoreAlbumInfo
    {

        [DataMember(Name = "targetmethod")]
        public int Targetmethod { get; set; }

        [DataMember(Name = "bigbooksjson")]
        public string Bigbooksjson { get; set; }

        [IgnoreDataMember]
        public ObservableCollection<TestJsonBookStoreAlbumInfoAreaBlock> Bigbooks { get; set; }

        [DataMember(Name = "id")]
        public int Id { get; set; }

        [DataMember(Name = "targetargument")]
        public string Targetargument { get; set; }

        [DataMember(Name = "name")]
        public string Name { get; set; }
    }

    [DataContract]
    public class TestJsonBookStoreAlbumInfoAreaBlock
    {

        [DataMember(Name = "bigbookid")]
        public int Bigbookid { get; set; }

        [DataMember(Name = "name")]
        public string Name { get; set; }

        [DataMember(Name = "progresstype")]
        public int Progresstype { get; set; }

        [DataMember(Name = "coverurl")]
        public string Coverurl { get; set; }

        [DataMember(Name = "lastpartname")]
        public string Lastpartname { get; set; }
    }
}